package com.shirley.callable;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ShirleyCaller implements Callable<String> {
    String label;

    public ShirleyCaller(String label) {
        this.label = label;
    }

    @Override
    public String call() throws Exception {
        System.out.println(label + " is running...");
        new Random().nextInt(1000, 9999);

        Thread.sleep(10000);
        Integer anInt = new Random().nextInt();
        if (anInt % 2 == 0) {
            System.out.println(label + " is done.");
            return label + ":" + anInt;
        } else {
            throw new RuntimeException("This is an exception from " + label);
        }

    }

    public static void main(String[] args) {
        Callable<String> callable = new ShirleyCaller("Callable task");
        FutureTask<String> task = new FutureTask<>(callable);

        new Thread(task).start();

        // get() will block until the thread terminated.
        try {
            String result = task.get();
            System.out.println("result=" + result);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            System.out.println("Catch an exception: " + e.getMessage());
        }
    }

}
